<template>
  <div class="dept">
    <div class="tree-search">
      <a-input v-model="searchKey" placeholder="请输入部门名称" allow-clear>
        <template #prefix>
          <icon-user />
        </template>
      </a-input>
    </div>
    <div class="tree-body">
      <a-tree
        v-model:selected-keys="selectedKeysModel"
        v-model:expanded-keys="expandedKeys"
        :data="treeData"
        @select="treeSelect"
      >
        <template #title="nodeData">
          <template v-if="getMatchIndex(nodeData?.title) < 0">{{
            nodeData?.title
          }}</template>
          <span v-else>
            {{ nodeData?.title?.substr(0, getMatchIndex(nodeData?.title)) }}
            <span style="color: var(--color-primary-light-4)">
              {{
                nodeData?.title?.substr(
                  getMatchIndex(nodeData?.title),
                  searchKey.length
                )
              }} </span
            >{{
              nodeData?.title?.substr(
                getMatchIndex(nodeData?.title) + searchKey.length
              )
            }}
          </span>
        </template>
      </a-tree></div
    >
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { getSelectOptions } from '@/utils/index';
  import type { TreeNodeData } from '@arco-design/web-vue/es/tree/interface';
  import { treeselect as getDeptTree } from '@/api/system/dept';

  // { getDeptTree }
  const originTreeData = ref<TreeNodeData[]>([]);
  const expandedKeys = ref<string[]>([]);
  const selectedKeysModel = ref([]);
  // 获取部门树
  const initDeptTree = async () => {
    const { code, msg, data } = await getDeptTree();
    if (code !== 200) {
      Message.error(msg);
      return;
    }
    originTreeData.value = getSelectOptions(data, {
      title: 'label',
      value: 'id',
      children: 'children',
      key: 'id',
    });
  };
  initDeptTree();

  const searchKey = ref('');

  function searchData(keyword: string) {
    expandedKeys.value = [];
    const loop = (data: Array<any>) => {
      const result: Array<any> = [];
      data.forEach((item) => {
        if (item.title.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
          result.push({ ...item });
          expandedKeys.value.push(`${item.pid}`);
        } else if (item.children) {
          const filterData = loop(item.children);
          if (filterData.length) {
            result.push({
              ...item,
              children: filterData,
            });
          }
        }
      });
      return result;
    };
    return loop(originTreeData.value);
  }
  const getMatchIndex = (title: string) => {
    if (!searchKey.value) return -1;
    return title.toLowerCase().indexOf(searchKey.value.toLowerCase());
  };

  const treeData = computed((): Array<TreeNodeData> => {
    if (!searchKey.value) return originTreeData.value;
    return searchData(searchKey.value);
  });
  const emit = defineEmits(['selectData']);
  const treeSelect = (selectedKeys: any, data: any) => {
    emit('selectData', data.node.value);
  };
</script>

<style lang="less" scoped>
  .dept {
    .tree-body {
      margin-top: 10px;
    }
  }
</style>
